from flask import request

from api.libs.RedPrint import RedPrint
from core.decorate import progress

api = RedPrint('model')


@api.route('/build/all')
@progress('批量归纳模型')
def build_model():
    from core.documents import Ask, TaskProgress
    from core.build_model import build_one_process
    checked = set()
    count = Ask.objects().count()
    index = 0
    for ask in Ask.objects().timeout(False):
        index += 1
        if not ask.url:
            continue
        if ask.url in checked:
            continue
        checked.add(ask.url)
        task = TaskProgress(key=ask.url, name=ask.url, count=100)
        used = False
        for i in build_one_process(ask.url):
            task.rate = i
            used = True
        if used:
            task.finish()
        yield int(index * 100 / count)


@api.route('/rebuild/one')
@progress('重新构建一个模型')
def rebuild_doc_one():
    from core.documents import APIModel
    from core.build_model import build_one_process
    relate_url = request.values['url']
    model = APIModel.objects(relate_url=relate_url).first()
    url = model.url
    APIModel.objects(relate_url=relate_url).delete()
    yield from build_one_process(url)


@api.route('/clean')
def clean_model():
    from core.documents import APIModel, RawValue
    APIModel.drop_collection()
    RawValue.drop_collection()
    return True


@api.route('/update')
@progress('更新模型')
def update_model():
    from core.documents import Question
    count = Question.objects(solved=True).count()
    index = 0
    for ans in Question.objects(solved=True):
        index += 1
        try:
            ans.update_model()
        except Exception:  # 解析出了问题就删除
            ans.delete()
        yield int(index / count * 100)
